// Device/pages/Analysis/sugar-component/index.js
import dayjs from 'dayjs';
import {
    fetchSugarDetail
} from '../../../../services/device';
const deepEqual = (a, b) => {
    if (a === b) return true;
    if (typeof a !== 'object' || typeof b !== 'object' || !a || !b) return false;
    const keysA = Object.keys(a),
        keysB = Object.keys(b);
    if (keysA.length !== keysB.length) return false;
    return keysA.every(key => keysB.includes(key) && deepEqual(a[key], b[key]));
};
const infoMappings = {
    '测量次数': 'measure_num',
    '异常测量次数': 'abnormal_num',
    '餐前血糖范围': 'before_val_radius',
    '餐前血糖平均值': 'before_val_vag',
    '餐后血糖范围': 'after_val_radius',
    '餐后血糖平均值': 'after_val_vag'
}

const Decimal = require('decimal.js');
Component({
    /**
     * 组件的属性列表
     */
    properties: {
        params: {
            type: Object,
            value: null,
            observer(newConfig, oldConfig) {
                if (!deepEqual(newConfig, oldConfig)) {
                    this.setData({
                        ...newConfig
                    }, () => {
                        this.searchDetail()
                    })
                }
            }
        }
    },
    /**
     * 组件的初始数据
     */
    data: {
        device_imei: null,
        first_config: {},
        second_config: {},
        infos: [{
            nodes: '',
            title: '测量次数'
        }, {
            nodes: '',
            title: '异常测量次数'
        }, {
            nodes: '',
            title: '餐前血糖范围'
        }, {
            nodes: '',
            title: '餐前血糖平均值'
        }, {
            nodes: '',
            title: '餐后血糖范围'
        }, {
            nodes: '',
            title: '餐后血糖平均值'
        }]
    },
    /**
     * 组件的方法列表
     */
    methods: {
        async searchDetail() {
            const {
                stime,
                otime,
                device_imei,
                user_tag
            } = this.data;
            const params = {
                stime,
                otime,
                device_imei,
                user_tag
            };
            if (this.data.currentIndex == 0) {
                delete params.otime;
            }
            const res = await fetchSugarDetail({
                ...params
            });
            switch (this.data.currentIndex) {
                case 0:
                    this.renderDayChart(res.data);
                    break;
                case 1:
                    this.renderWeekChart(res.data);
                    break;
                case 2:
                    this.renderMonthChart(res.data);
                    break;
                default:
                    break;
            }
            let {
                blood_sugar_obj
            } = res.data;

            let third_config = {
                tooltip: {
                    trigger: 'item',
                    textStyle: {
                        align: 'left',
                        textShadowBlur: 10, // 重点
                        textShadowColor: 'transparent', // 重点
                    },
                },
                legend: {
                    top: 0
                },
                grid: {
                    bottom: 0,
                    containLabel: true
                },
                legend: {
                    orient: 'horizontal',
                    top: 'top'
                },
                series: [{
                    type: 'pie',
                    radius: ['30%', '55%'],
                    center: ['50%', '60%'],
                    avoidLabelOverlap: false,
                    labelLine: {
                        show: true
                    },
                    data: [{
                        value: blood_sugar_obj.normal_num,
                        name: '正常',
                        itemStyle: {
                            color: '#73C0DE',
                            borderRadius: 5
                        }
                    }, {
                        value: blood_sugar_obj.abnormal_num,
                        name: '异常',
                        itemStyle: {
                            color: '#EE6666',
                            borderRadius: 5
                        }
                    }]
                }]
            }
            let infos = this.data.infos;
            infos.forEach(item => {
                switch (item.title) {
                    case '测量次数':
                        item.nodes = `<font>${blood_sugar_obj[infoMappings[item.title]]}次</font>`
                        break;
                    case '异常测量次数':
                        item.nodes = `<font>${ blood_sugar_obj[infoMappings[item.title]] }次</font>`
                        break;
                    case '餐前血糖范围':
                        item.nodes = `<font>${ blood_sugar_obj[infoMappings[item.title]] }mmol/L</font>`
                        break;
                    case '餐前血糖平均值':
                        item.nodes = `<font>${ blood_sugar_obj[infoMappings[item.title]] }mmol/L</font>`
                        break;
                    case '餐后血糖范围':
                        item.nodes = `<font>${ blood_sugar_obj[infoMappings[item.title]] }mmol/L</font>`
                        break;
                    case '餐后血糖平均值':
                        item.nodes = `<font>${ blood_sugar_obj[infoMappings[item.title]] }mmol/L</font>`
                        break;
                    case '测量次数':
                        item.nodes = `<font>${ blood_sugar_obj[infoMappings[item.title]] }次</font>`
                        break;
                    default:
                        break;
                }
            })
            this.setData({
                third_config,
                infos,
                text: this.renderText(blood_sugar_obj)
            })
        },
        renderText({
            normal_num,
            abnormal_num,
            before_val_radius,
            after_val_radius,
            measure_num,
            highabnormal_num,
            lowabnormal_num
        }) {
            let timePeriod = this.data.currentIndex == 0 ? '日' : this.data.currentIndex == 1 ? '周' : this.data.currentIndex == 2 ? '月' : '';

            // 测量次数不足
            if (measure_num < 5) {
                return '您最近的血糖数据不足，无法为您提供血糖异常分析服务。测量次数达到5次以上即可查看分析解读。';
            }

            // 基础消息内容
            let baseMessage = `本${timePeriod}您测量了${measure_num}次血糖，其中正常${normal_num}次，异常${abnormal_num}次。餐前异常血糖最高${before_val_radius.split('-')[0]}mmol/L、最低${before_val_radius.split('-')[1]}mmol/L，餐后异常血糖最高${after_val_radius.split('-')[0]}mmol/L、最低${after_val_radius.split('-')[1]}mmol/L，`;

            // 当没有异常的情况下
            if (abnormal_num === 0) {
                return `本${timePeriod}您测量了${measure_num}次血糖，全部正常。根据数据显示您的血糖正常，请保持良好的生活习惯，并持续观察血糖。`;
            }

            // 异常次数占比小于50%
            if ((abnormal_num / measure_num) < 0.5) {
                return `${baseMessage}根据数据显示您的血糖存在异常，请坚持合理饮食、注意休息、适当锻炼，并持续观察血糖变化。`;
            }

            // 高异常和低异常相等
            if (highabnormal_num === lowabnormal_num) {
                return `${baseMessage}根据数据显示您的血糖存在异常，请坚持合理饮食、注意休息、适当锻炼，并持续观察血糖变化。`;
            }

            // 高异常大于低异常
            if (highabnormal_num > lowabnormal_num) {
                return `${baseMessage}根据数据显示您的血糖存在异常，建议您平时合理配餐、少食多餐，避免快餐、糖果、饮料等高糖高脂的食物，选择低糖低脂的食物，如全麦面包、燕麦、水果、蔬菜、瘦肉等，同时规律生活、适量运动，提高身体的代谢能力，加速糖分的消耗，稳定血糖水平。`;
            }

            // 低异常大于高异常
            if (highabnormal_num < lowabnormal_num) {
                return `${baseMessage}根据数据显示您的血糖存在异常，建议您平时随身携带糖果、少食多餐，适量补充维生素如菠菜、木耳、猪肝等，同时进行适当有氧运动，如散步、快走等，避免剧烈运动，并持续观察血糖变化。`;
            }
        },
        renderDayChart({
            before_list,
            after_list
        }) {
            let first_config = {
                tooltip: {
                    show: true,
                    confine: true,
                    trigger: 'axis',
                    textStyle: {
                        align: 'left',
                        textShadowBlur: 10, // 重点
                        textShadowColor: 'transparent', // 重点
                    },
                },
                title: {
                    subtext: 'mmol/L',
                    subtextStyle: {
                        height: 100,
                        lineHeight: 20
                    },
                },
                legend: {
                    align: 'left',
                    itemHeight: 6,
                    itemWidth: 10,
                    show: true,
                    top: 'top'
                },
                xAxis: {
                    type: 'category',
                    data: before_list.map(item => {
                        return dayjs(item.measuring_time).format('HH:mm')
                    })
                },
                yAxis: {
                    type: 'value',
                    nameGap: 10,
                    splitLine: {
                        lineStyle: {
                            type: 'dashed'
                        },
                        show: true
                    }
                },
                graphic: {
                    invisible: before_list.length ? true : false,
                    left: 'center',
                    silent: true,
                    style: {
                        fill: 'black',
                        fontSize: '20px',
                        fontWeight: 'normal',
                        text: '暂无数据'
                    },
                    top: 'middle',
                    type: 'text'
                },
                grid: {
                    bottom: 10,
                    left: 10,
                    right: 10,
                    top: '20%',
                    show: false,
                    containLabel: true
                },
                series: [{
                    name: '餐前',
                    data: before_list.map(item => {
                        return item.blood_glucose_val
                    }),
                    label: {
                        show: true,
                        position: 'top'
                    },
                    type: 'line',
                    itemStyle: {
                        color: 'rgba(118, 203, 68)'
                    },
                    lineStyle: {
                        color: 'rgba(118, 203, 68)'
                    },
                    areaStyle: {
                        color: {
                            type: 'linear',
                            x: 0,
                            y: 0,
                            x2: 0,
                            y2: 1,
                            colorStops: [{
                                    offset: 0,
                                    color: 'rgba(118, 203, 68)' // 0% 处的颜色
                                },
                                {
                                    offset: 1,
                                    color: 'rgba(255, 255, 255)' // 100% 处的颜色
                                }
                            ],
                            global: false // 缺省为 false
                        }
                    },
                }]
            }
            let second_config = {
                tooltip: {
                    show: true,
                    confine: true,
                    trigger: 'axis',
                    textStyle: {
                        align: 'left',
                        textShadowBlur: 10, // 重点
                        textShadowColor: 'transparent', // 重点
                    },
                },
                title: {
                    subtext: 'mmol/L',
                    subtextStyle: {
                        height: 100,
                        lineHeight: 20
                    },
                },
                legend: {
                    align: 'left',
                    itemHeight: 6,
                    itemWidth: 10,
                    show: true,
                    top: 'top'
                },
                xAxis: {
                    type: 'category',
                    data: after_list.map(item => {
                        return dayjs(item.measuring_time).format('HH:mm')
                    })
                },
                yAxis: {
                    type: 'value',
                    nameGap: 10,
                    splitLine: {
                        lineStyle: {
                            type: 'dashed'
                        },
                        show: true
                    }
                },
                graphic: {
                    invisible: after_list.length ? true : false,
                    left: 'center',
                    silent: true,
                    style: {
                        fill: 'black',
                        fontSize: '20px',
                        fontWeight: 'normal',
                        text: '暂无数据'
                    },
                    top: 'middle',
                    type: 'text'
                },
                grid: {
                    bottom: 10,
                    left: 10,
                    right: 10,
                    top: '20%',
                    show: false,
                    containLabel: true
                },
                series: [{
                    name: '餐后',
                    data: after_list.map(item => {
                        return item.blood_glucose_val
                    }),
                    label: {
                        show: true,
                        position: 'top'
                    },
                    type: 'line',
                    lineStyle: {
                        color: '#EF713A'
                    },
                    itemStyle: {
                        color: '#EF713A'
                    },
                    areaStyle: {
                        color: {
                            type: 'linear',
                            x: 0,
                            y: 0,
                            x2: 0,
                            y2: 1,
                            colorStops: [{
                                    offset: 0,
                                    color: 'rgba(239, 113, 58, 1)' // 0% 处的颜色
                                },
                                {
                                    offset: 1,
                                    color: 'rgba(255, 255, 255)' // 100% 处的颜色
                                }
                            ],
                            global: false // 缺省为 false
                        }
                    },
                }]
            }
            console.log(JSON.stringify(first_config), JSON.stringify(second_config))
            this.setData({
                first_config,
                second_config
            })
        },
        renderWeekChart({
            list
        }) {
            let before = [],
                after = [];
            list.map(t => {
                if (!t.before_max_value && !t.before_min_value) {
                    before.push(null)
                } else {
                    before.push((t.before_max_value * 100 - t.before_min_value * 100) / 100)
                }
                if (!t.after_max_value && !t.after_min_value) {
                    after.push(null)
                } else {
                    after.push((t.after_max_value * 100 - t.after_min_value * 100) / 100)
                }
            })
            console.log(before)
            let first_config = {
                graphic: {
                    invisible: list.length ? true : false,
                    left: 'center',
                    silent: true,
                    style: {
                        fill: 'black',
                        fontSize: '20px',
                        fontWeight: 'normal',
                        text: '暂无数据'
                    },
                    top: 'middle',
                    type: 'text'
                },
                grid: {
                    bottom: 10,
                    left: 10,
                    right: 10,
                    top: '20%',
                    show: false,
                    containLabel: true
                },
                legend: {
                    align: 'left',
                    itemHeight: 6,
                    itemWidth: 10,
                    show: true,
                    top: 'top'
                },
                tooltip: {
                    show: true,
                    confine: true,
                    trigger: 'axis',
                    formatter: function (params) {
                        return params[0].axisValue + '\n' + params[1].seriesName + '：' + params[0].value + '~' + ((params[0].value + params[1].value) ? (params[0].value + params[1].value).toFixed(1) : 0)
                    },
                    textStyle: {
                        align: 'left',
                        textShadowBlur: 10, // 重点
                        textShadowColor: 'transparent', // 重点
                    },
                },
                title: {
                    subtext: 'mmol/L',
                    subtextStyle: {
                        height: 100,
                        lineHeight: 20
                    },
                },
                xAxis: {
                    type: 'category',
                    data: list.map(item => {
                        return item.week
                    })
                },
                yAxis: {
                    type: 'value',
                    nameGap: 10,
                    splitLine: {
                        lineStyle: {
                            type: 'dashed'
                        },
                        show: true
                    }
                },
                series: [{
                        name: null,
                        stack: 'bar',
                        type: 'bar',
                        itemStyle: {
                            borderColor: 'transparent',
                            color: 'transparent',

                        },
                        barWidth: 10,
                        emphasis: {
                            itemStyle: {
                                borderColor: 'transparent',
                                color: 'transparent'
                            }
                        },
                        data: list.map(t => {
                            return t.before_min_value
                        })
                    },
                    {
                        name: '餐前',
                        type: 'bar',
                        stack: 'bar',
                        data: before,
                        itemStyle: {
                            color: 'rgba(120, 205, 69, 1)',
                            borderColor: 'rgba(120, 205, 69, 1)',
                            borderWidth: 2,
                            borderRadius: 20
                        }
                    }
                ]
            }
            let second_config = {
                graphic: {
                    invisible: list.length ? true : false,
                    left: 'center',
                    silent: true,
                    style: {
                        fill: 'black',
                        fontSize: '20px',
                        fontWeight: 'normal',
                        text: '暂无数据'
                    },
                    top: 'middle',
                    type: 'text'
                },
                grid: {
                    bottom: 10,
                    left: 10,
                    right: 10,
                    top: '20%',
                    show: false,
                    containLabel: true
                },
                legend: {
                    align: 'left',
                    itemHeight: 6,
                    itemWidth: 10,
                    show: true,
                    top: 'top'
                },
                tooltip: {
                    show: true,
                    confine: true,
                    trigger: 'axis',
                    formatter: function (params) {
                        return params[0].axisValue + '\n' + params[1].seriesName + '：' + params[0].value + '~' + ((params[0].value + params[1].value) ? (params[0].value + params[1].value).toFixed(1) : 0)
                    },
                    textStyle: {
                        align: 'left',
                        textShadowBlur: 10, // 重点
                        textShadowColor: 'transparent', // 重点
                    },
                },
                title: {
                    subtext: 'mmol/L',
                    subtextStyle: {
                        height: 100,
                        lineHeight: 20
                    },
                },
                xAxis: {
                    type: 'category',
                    data: list.map(item => {
                        return item.week
                    })
                },
                yAxis: {
                    type: 'value',
                    nameGap: 10,
                    splitLine: {
                        lineStyle: {
                            type: 'dashed'
                        },
                        show: true
                    }
                },
                series: [{
                        name: null,
                        stack: 'bar',
                        type: 'bar',
                        itemStyle: {
                            borderColor: 'transparent',
                            color: 'transparent',

                        },
                        barWidth: 10,
                        emphasis: {
                            itemStyle: {
                                borderColor: 'transparent',
                                color: 'transparent'
                            }
                        },
                        data: list.map(t => {
                            return t.after_min_value
                        })
                    },
                    {
                        name: '餐后',
                        type: 'bar',
                        stack: 'bar',
                        data: after,
                        itemStyle: {
                            color: 'rgba(239, 113, 58, 1)',
                            borderColor: 'rgba(239, 113, 58, 1)',
                            borderWidth: 2,
                            borderRadius: 20
                        }
                    }
                ]
            }
            this.setData({
                first_config,
                second_config
            })
        },
        renderMonthChart({
            list
        }) {
            let before = [],
                after = [];
            list.map(t => {
                if (!t.before_max_value && !t.before_min_value) {
                    before.push(null)
                } else {
                    before.push((t.before_max_value * 100 - t.before_min_value * 100) / 100)
                }
                if (!t.after_max_value && !t.after_min_value) {
                    after.push(null)
                } else {
                    after.push((t.after_max_value * 100 - t.after_min_value * 100) / 100)
                }
            })
            let first_config = {
                graphic: {
                    invisible: list.length ? true : false,
                    left: 'center',
                    silent: true,
                    style: {
                        fill: 'black',
                        fontSize: '20px',
                        fontWeight: 'normal',
                        text: '暂无数据'
                    },
                    top: 'middle',
                    type: 'text'
                },
                legend: {
                    align: 'left',
                    itemHeight: 6,
                    itemWidth: 10,
                    show: true,
                    top: 'top'
                },
                grid: {
                    bottom: 10,
                    left: 10,
                    right: 10,
                    top: '20%',
                    show: false,
                    containLabel: true
                },
                tooltip: {
                    show: true,
                    confine: true,
                    trigger: 'axis',
                    formatter: function (params) {
                        return params[0].axisValue + '\n' + params[1].seriesName + '：' + params[0].value + '~' + ((params[0].value + params[1].value) ? (params[0].value + params[1].value).toFixed(1) : 0)
                    },
                    textStyle: {
                        align: 'left',
                        textShadowBlur: 10, // 重点
                        textShadowColor: 'transparent', // 重点
                    },
                },
                title: {
                    subtext: 'mmol/L',
                    subtextStyle: {
                        height: 100,
                        lineHeight: 20
                    },
                },
                xAxis: {
                    type: 'category',
                    data: list.map(item => {
                        return item.time
                    })
                },
                yAxis: {
                    type: 'value',
                    nameGap: 10,
                    splitLine: {
                        lineStyle: {
                            type: 'dashed'
                        },
                        show: true
                    }
                },
                series: [{
                        name: null,
                        stack: 'bar',
                        type: 'bar',
                        itemStyle: {
                            borderColor: 'transparent',
                            color: 'transparent',

                        },
                        barWidth: 10,
                        emphasis: {
                            itemStyle: {
                                borderColor: 'transparent',
                                color: 'transparent'
                            }
                        },
                        data: list.map(t => {
                            return t.before_min_value
                        })
                    },
                    {
                        name: '餐前',
                        type: 'bar',
                        stack: 'bar',
                        data: before,
                        itemStyle: {
                            color: 'rgba(120, 205, 69, 1)',
                            borderColor: 'rgba(120, 205, 69, 1)',
                            borderWidth: 2,
                            borderRadius: 20
                        }
                    }
                ]
            }
            let second_config = {
                graphic: {
                    invisible: list.length ? true : false,
                    left: 'center',
                    silent: true,
                    style: {
                        fill: 'black',
                        fontSize: '20px',
                        fontWeight: 'normal',
                        text: '暂无数据'
                    },
                    top: 'middle',
                    type: 'text'
                },
                legend: {
                    align: 'left',
                    itemHeight: 6,
                    itemWidth: 10,
                    show: true,
                    top: 'top'
                },
                grid: {
                    bottom: 10,
                    left: 10,
                    right: 10,
                    top: '20%',
                    show: false,
                    containLabel: true
                },
                tooltip: {
                    show: true,
                    confine: true,
                    trigger: 'axis',
                    formatter: function (params) {
                        return params[0].axisValue + '\n' + params[1].seriesName + '：' + params[0].value + '~' + ((params[0].value + params[1].value) ? (params[0].value + params[1].value).toFixed(1) : 0)
                    },
                    textStyle: {
                        align: 'left',
                        textShadowBlur: 10, // 重点
                        textShadowColor: 'transparent', // 重点
                    },
                },
                title: {
                    subtext: 'mmol/L',
                    subtextStyle: {
                        height: 100,
                        lineHeight: 20
                    },
                },
                xAxis: {
                    type: 'category',
                    data: list.map(item => {
                        return item.time
                    })
                },
                yAxis: {
                    type: 'value',
                    nameGap: 10,
                    splitLine: {
                        lineStyle: {
                            type: 'dashed'
                        },
                        show: true
                    }
                },
                series: [{
                        name: null,
                        stack: 'bar',
                        type: 'bar',
                        itemStyle: {
                            borderColor: 'transparent',
                            color: 'transparent',

                        },
                        barWidth: 10,
                        emphasis: {
                            itemStyle: {
                                borderColor: 'transparent',
                                color: 'transparent'
                            }
                        },
                        data: list.map(t => {
                            return t.after_min_value
                        })
                    },
                    {
                        name: '餐后',
                        type: 'bar',
                        stack: 'bar',
                        data: after,
                        itemStyle: {
                            color: 'rgba(239, 113, 58, 1)',
                            borderColor: 'rgba(239, 113, 58, 1)',
                            borderWidth: 2,
                            borderRadius: 20
                        }
                    }
                ]
            }
            this.setData({
                first_config,
                second_config
            })
        }
    }
})